package com.jfl.core.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;

import com.google.code.kaptcha.Constants;
import com.jfl.core.utils.ShiroUtils;

/**
 * 验证码过滤器
 * 
 * @author 赵炎
 * @version [V1.00, 2018年12月5日]
 * @see [相关类/方法]
 * @since V1.00
 */
public class CaptchaValidateFilter extends AccessControlFilter
{
    /**
     * 是否开启验证码
     */
    private boolean captchaEnabled = true;
    
    /**
     * 验证码类型
     */
    private String captchaType = "math";
    
    public void setCaptchaEnabled(boolean captchaEnabled)
    {
        this.captchaEnabled= captchaEnabled;
    }
    
    public void setCaptchaType(String captchaType)
    {
        this.captchaType = captchaType;
    }
    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception
    {
        request.setAttribute("captchaEnabled", captchaEnabled);
        request.setAttribute("captchaType", captchaType);
        return super.onPreHandle(request, response, mappedValue);
    }
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception
    {
        HttpServletRequest req = (HttpServletRequest)request;
        if(captchaEnabled== false ||"post".equalsIgnoreCase(req.getMethod()))
        {
            return true;
        }
        return validateRequest(req, req.getParameter("validateCode"));
    }
    
    /** 
     * 验证码校验
     * @param req
     * @param validateCode
     * @return
     * @see [类、类#方法、类#成员]
     */
    private boolean validateRequest(HttpServletRequest req, String validateCode)
    {
        Object obj = ShiroUtils.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        String code = String.valueOf(obj != null ? obj : "");
        if (StringUtils.isEmpty(validateCode) || !validateCode.equalsIgnoreCase(code))
        {
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception
    {
        request.setAttribute("captcha", "captchaError");
        return false;
    }
    
}
